<template>
  <div class="search-suggest-container">
    <van-cell
      v-for="(sug, i) in suggesstionList"
      :key="i"
      @click="doSearch(sug)"
      icon="search"
    >
      <div slot="title" v-html="pickKeyWords(sug)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggest',
  data() {
    return {
      suggesstionList: []
    }
  },
  props: {
    searchContent: {
      type: String,
      required: true
    }
  },
  methods: {
    async getSuggestions(q) {
      try {
        const { data: res } = await getSearchSuggestions(q)
        this.suggesstionList = res.data.options
      } catch (error) {
        this.$toast.fail('服务器繁忙，请稍后再试哟')
      }
    },
    // 点击建议选项触发父组件的自定义搜索事件
    doSearch(sug) {
      this.$emit('doSearch', sug)
    },
    // 将搜索关键词设置高亮(用带类名的标签包裹)
    heightLight(str) {
      return `<span class="height-light">${str}</span>`
    },
    // 使用正则全局替换
    pickKeyWords(sug) {
      const reg = new RegExp(this.searchContent, 'gi')
      return sug.replace(reg, this.heightLight(this.searchContent))
    }
  },
  /*
  因为搜索关键词是父组件传递过来的，
  子组件使用监视属性，
  数据一旦变化则执行建议请求，
  改变当前组件接受请求的变量，
  从而vue帮我们实现响应式更新dom */
  watch: {
    searchContent: {
      immediate: true,
      handler: debounce(function (newVal) {
        this.getSuggestions(newVal)
      }, 200)
    }
  }
}
</script>

<style lang="less" scoped>
.search-suggest-container {
  /deep/ .height-light {
    color: red !important;
  }
}
</style>
